package interview;

import java.util.LinkedList;

public class interview_01_06 {
    public String compressString(String S) {
        int orilen=S.length();
        if(orilen<=2) return S;
        LinkedList<int[]> list=new LinkedList<>();
        char[] s=S.toCharArray();
        int[] tmp=new int[2];
        tmp[0]=s[0]-'A';
        tmp[1]=1;
        list.add(tmp);
        for(int i=1;i<orilen;++i){
            if(s[i]-'A'==list.getLast()[0]){
//                list.set(list.size()-1,new int[]{list.getLast()[0],list.getLast()[1]+1});
                list.getLast()[1]+=1;
            }
            else{
                int[] temp=new int[2];
                temp[0]=s[i]-'A';
                temp[1]=1;
                list.add(temp);
            }
        }
        StringBuilder stringBuilder=new StringBuilder();
        while(!list.isEmpty()){
            stringBuilder.append((char)('A'+list.getFirst()[0]));
            stringBuilder.append(list.removeFirst()[1]);
        }
        if(stringBuilder.toString().length()>=orilen) return S;
        return stringBuilder.toString();
    }
}
